const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')

router.get('/list', (req, res) => {
  fs.readFile(path.join(__dirname, 'data.json'), 'utf-8', (err, data) => {
    res.send(data)
  })
})
router.post('/add', (req, res) => {
  const title = req.body.data
  fs.readFile(path.join(__dirname, 'data.json'), 'utf-8', (err, data) => {
    data = JSON.parse(data)
    const isOnlyValue = data.some(item => {
      if (item.title === title) return true
    })
    if (isOnlyValue === true) return res.send({
      message: '添加信息失败!',
      status: 400
    })
    data.push({ title, option: "删除" })
    data = JSON.stringify(data)
    fs.writeFile(path.join(__dirname, 'data.json'), data, err => {
      if (err !== null) {
        console.log(err)
        return res.send({
          message: '添加信息失败!',
          status: 400
        })
      } else {
        res.send({
          message: '添加信息成功!',
          status: 200,
          data: {
            title,
            option: '删除'
          }
        })
      }
    })
  })
})
router.delete('/delete/:value', (req, res) => {
  // console.log(req.params.value) // 保存时为什么会打印,并没有在html页面进行dom操作发送请求
  const deletValue = req.params.value
  fs.readFile(path.join(__dirname, 'data.json'), 'utf-8', (err, data) => {
    if (err !== null) return console.log(err)
    data = JSON.parse(data)
    const index = data.findIndex(item => item.title === deletValue)
    const title = data.splice(index,1)
    data = JSON.stringify(data)
    fs.writeFile(path.join(__dirname, 'data.json'), data, err => {
      if (err !== null) return console.log(err)
      res.send({
        message: '删除信息成功!',
        status: 200,
        data: {
          title,
          option: '删除'
        }
      })
    })
  })
})
router.put('/editor', (req, res) => {
  let { oldValue, newValue }  = req.body
  // console.log(editorValue)
  fs.readFile(path.join(__dirname, 'data.json'), 'utf-8', (err, data) => {
    if (err !== null) return console.log(err)
    data = JSON.parse(data)
    const isOnlyValue = data.some(item => item.title === newValue)
    if (isOnlyValue === true) {
      return res.send({
        message: '修改的内容已存在,请重新输入',
        status: 400
      })
    } else {
      data.find(item => {
        if (item.title === oldValue) {
          item.title = newValue
          return true
        }
      })
      fs.writeFile(path.join(__dirname, 'data.json'), JSON.stringify(data), err => {
        if (err !== null) return console.log(err)
        return res.send({
          message: '修改的内容修改成功!',
          status: 200
        })
      })
    }
  })
})
module.exports = router